package com.zxbit.flash.ui.activity.auth;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.zxbit.flash.R;
import com.zxbit.flash.adapter.ImgListAdapter;
import com.zxbit.flash.base.BaseTitleActivity;
import com.zxbit.flash.camera.CameraPhotoActivity;
import com.zxbit.flash.common.AuthRouter;
import com.zxbit.flash.common.Constant;
import com.zxbit.flash.common.RouterMap;
import com.zxbit.flash.common.UserInfo;
import com.zxbit.flash.mvpview.ImgMvpView;
import com.zxbit.flash.mvpview.PhotoAuthMvpView;
import com.zxbit.flash.permission.IPermisson;
import com.zxbit.flash.permission.Permission;
import com.zxbit.flash.presenter.ImgPresenter;
import com.zxbit.flash.presenter.PhotoAuthPresenter;
import com.zxbit.flash.bean.AuthInfoData;
import com.zxbit.flash.response.AuthInfoResponse;
import com.zxbit.flash.response.BlankResponse;
import com.zxbit.flash.bean.IdentityData;
import com.zxbit.flash.response.IdentityResponse;
import com.zxbit.flash.bean.ImgsListData;
import com.zxbit.flash.utils.FileUtils;
import com.zxbit.flash.utils.ToastUtils;
import com.zxbit.flash.view.dialog.SelectImgDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

@Route(name = "补充资料认证", path = RouterMap.PHOTO_AUTH_PAGE)
public class PhotoAuthActivity extends BaseTitleActivity implements ImgMvpView, PhotoAuthMvpView,
        IPermisson, SelectImgDialog.SelectImgDialogClickListener {
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.tv_next_step)
    TextView tvNextStep;
    @Autowired(name = Constant.IS_BACK)
    boolean is_back;
    private ImgListAdapter adapter;

    private ImgPresenter presenter;
    private PhotoAuthPresenter photoAuthPresenter;
    private List<ImgsListData.ImgPathListBean> data = new ArrayList<>();
    private int mClickGridItemPosition;
    private Permission permission;
    private Uri tempPhotoUri;
    private List<IdentityData.ImageInfoBean> imageInfoParams = new ArrayList<>();


    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        GridLayoutManager gl = new GridLayoutManager(this, 2);
        initGridData();
        adapter = new ImgListAdapter(this, data);
        rv.setLayoutManager(gl);
        rv.setAdapter(adapter);
        rv.setItemViewCacheSize(0);
        adapter.setOnItemClickListener(new ImgListAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                permission.uploadImage(position);
            }
        });

    }

    @Override
    protected void onUIReady() {
        ARouter.getInstance().inject(this);

        permission = new Permission(this, this);
        presenter = new ImgPresenter(this);
        photoAuthPresenter = new PhotoAuthPresenter(this);
        GridLayoutManager gl = new GridLayoutManager(this, 3);
        rv.setLayoutManager(gl);

        if (UserInfo.isShowUserInformation()) {
            photoAuthPresenter.getAdditionalInfo();
        }
        if (is_back) {
            tvNextStep.setText(R.string.save_change);
        }
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_photo_auth;
    }

    @Override
    public String getPageTitle() {
        return getStringResource(R.string.custom_auth_page_title);
    }

    public void initGridData() {
        data.clear();
        for (int i = 0; i < 10; i++) {
            ImgsListData.ImgPathListBean bean = new ImgsListData.ImgPathListBean();
            bean.setImageType(i + 3);
            data.add(bean);
        }
    }

    /**
     * 打开相机
     *
     * @param position
     */
    private void openTakePhoto(final int position) {
        Intent intent = new Intent(this, CameraPhotoActivity.class);
        startActivityForResult(intent, position);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent ondata) {
        super.onActivityResult(requestCode, resultCode, ondata);
        if (requestCode >= 0 && requestCode <= 9) {
            File file = new File(ondata.getStringExtra("filename"));

            String filename = ondata.getStringExtra("filename");
            Uri PhotoUri = Uri.fromFile(file);
            //设置图片的
            if (PhotoUri != null) {
                compressImgAndDisPlay(PhotoUri, requestCode);
            }
            ImgsListData.ImgPathListBean bean = data.get(requestCode);
            bean.setNativeFileUri(Uri.fromFile(file));
            data.set(requestCode, bean);
            adapter.notifyItemChanged(requestCode);
        } else if (requestCode >= 12) {
            if (resultCode == RESULT_OK) {
                try {
                    //获取系统返回的照片的Uri
                    Uri selectedImage = ondata.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    //从系统表中查询指定Uri对应的照片
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn,
                            null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    //获取照片路径
                    String path = cursor.getString(columnIndex);
                    cursor.close();
                    tempPhotoUri = Uri.fromFile(new File(path));
                    compressImgAndDisPlay(tempPhotoUri, requestCode - 12);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


    }

    @Override
    public void onTakePhotoClick() {

        openTakePhoto(mClickGridItemPosition);
    }

    @Override
    public void onSelectPictureClick() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media
                .EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, mClickGridItemPosition + 12);
    }

    public void compressImgAndDisPlay(final Uri sourceImgUri, final int compressType) {

        Luban.with(this).ignoreBy(500).load(sourceImgUri).setTargetDir(FileUtils.getCachePicDir1()
        ).setCompressListener(new OnCompressListener() {
            @Override
            public void onStart() {
                showLoadingView();
            }

            @Override
            public void onSuccess(File file) {
                presenter.uploadImg(compressType + 3, file);
                dismissLoadingView();
                ImgsListData.ImgPathListBean bean = data.get(compressType);
                bean.setNativeFileUri(Uri.fromFile(file));
                data.set(compressType, bean);
                adapter.notifyItemChanged(compressType);

            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingView();
            }
        }).launch();

    }

    @OnClick(R.id.tv_next_step)
    public void commit() {
        boolean flag = false;
        for (ImgsListData.ImgPathListBean bean : data) {
            if (bean.getImageType() == 5) {
                if (bean.getNativeFileUri() != null || !TextUtils.isEmpty(bean.getImagePathUrl()))
                    flag = true;
            }
        }
        if (!flag) {
            ToastUtils.showShort(this, R.string.auth_photo_account_card_toast);
            return;
        }

        photoAuthPresenter.saveAddInformation(imageInfoParams);
        showLoadingView();

    }


    @Override
    public void onSuccess(int result) {
        mClickGridItemPosition = result;
        openTakePhoto(mClickGridItemPosition);
    }

    @Override
    public void onGetDataNext(AuthInfoResponse response) {
        dismissLoadingView(); // 获取
        if (response.getStatus() == Constant.HTTP_OK) {
            List<AuthInfoData.AdditionalInformationBean.ImageListBean> imageList = response
                    .getData().getAdditionalInformation().getImageList();
            if (imageList == null || imageList.size() == 0) return;
            for (int i = 0; i < imageList.size(); i++) {
                ImgsListData.ImgPathListBean bean = new ImgsListData.ImgPathListBean();
                bean.setImageType(imageList.get(i).getFileType());
                bean.setImagePathUrl(imageList.get(i).getImageUrl());
                switch (bean.getImageType()) {
                    case 3:
                        data.set(0, bean);
                        break;
                    case 4:
                        data.set(1, bean);
                        break;
                    case 5:
                        data.set(2, bean);
                        break;
                    case 6:
                        data.set(3, bean);
                        break;
                    case 7:
                        data.set(4, bean);
                        break;
                    case 8:
                        data.set(5, bean);
                        break;
                    case 9:
                        data.set(6, bean);
                        break;
                    case 10:
                        data.set(7, bean);
                        break;
                    case 11:
                        data.set(8, bean);
                        break;
                    case 12:
                        data.set(9, bean);
                        break;
                    default:
                        break;
                }
                imageInfoParams.clear();
                for (AuthInfoData.AdditionalInformationBean.ImageListBean imageListBean :
                        response.getData().getAdditionalInformation().getImageList()) {

                    IdentityData.ImageInfoBean infoBean = new IdentityData.ImageInfoBean();
                    infoBean.setImageName(imageListBean.getImageName());
                    infoBean.setFileType(imageListBean.getFileType());
                    infoBean.setImagePath(imageListBean.getImagePath());
                    infoBean.setImageUrl(imageListBean.getImageUrl());
                    imageInfoParams.add(infoBean);
                }


            }
            adapter.notifyDataSetChanged();
        } else {
            ToastUtils.showShort(this, response.getMessage());
        }
    }

    @Override
    public void onGetDataNext(BlankResponse response) {
        dismissLoadingView();
        if (!is_back) {
            AuthRouter.getInstance().jumpNextPager(PhotoAuthActivity.this, RouterMap
                    .PHOTO_AUTH_PAGE);
        } else {
            finish();
        }
    }

    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
    }

    @Override
    public void onGetDataNext(IdentityResponse identityResponse, int... type) {
        dismissLoadingView();
        if (identityResponse.getStatus() != Constant.HTTP_OK) {
            ToastUtils.showShort(this, identityResponse.getMessage());
            return;
        }
        for (IdentityData.ImageInfoBean bean : imageInfoParams) {
            if (bean.getFileType() == identityResponse.getData().getImageInfo().getFileType()) {
                imageInfoParams.remove(bean);
                imageInfoParams.add(identityResponse.getData().getImageInfo());
                return;

            }
        }
        imageInfoParams.add(identityResponse.getData().getImageInfo());
    }
}
